//
//  AppController.m
//  SpeakLine
//
//  Created by KaiKai on 11-6-24.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AppController.h"


@implementation AppController
@synthesize btnStop;

- (id)init
{
	[super init];
	NSLog(@"init");
	speechSynth = [[NSSpeechSynthesizer alloc] initWithVoice:nil];
	[speechSynth setDelegate:(id < NSSpeechSynthesizerDelegate >)self];
	voiceList = [[NSSpeechSynthesizer availableVoices] retain];
	return self;
}

- (IBAction)sayIt:(id)sender
{
	NSString *string = [textField stringValue];
	
	if ([string length] == 0)
	{
		NSLog(@"string from %@ is of zero-length", textField);
		return;
	}
	
	[speechSynth startSpeakingString:string];
	
	NSLog(@"Have started to say: %@", string);
	
	[btnStop setEnabled:YES];
	[btnStart setEnabled:NO];
	[tableView setEnabled:NO];
}

- (IBAction)stopIt:(id)sender
{
	NSLog(@"stoping");
	[speechSynth stopSpeaking];
}

- (void)awakeFromNib
{
	[textField setStringValue:@"Xie xie guo jia, guo jia is garbage"];
	[btnStop setEnabled:NO];
	
	NSString *defaultVoice = [NSSpeechSynthesizer defaultVoice];
	int defaultRow = [voiceList indexOfObject:defaultVoice];
	[tableView selectRow:defaultRow byExtendingSelection:NO];
	[tableView scrollRowToVisible:defaultRow];
}

- (void)speechSynthesizer:(NSSpeechSynthesizer *)sender
		didFinishSpeaking:(BOOL)finishedSpeaking
{
	NSLog(@"complete = %d", finishedSpeaking);
	[btnStop setEnabled:NO];
	[btnStart setEnabled:YES];
	[tableView setEnabled:YES];
}

- (int)numberOfRowsInTableView:(NSTabView *)tv
{
	return (int)[voiceList count];
}

- (id)tableView:(NSTableView *)tv
		objectValueForTableColumn:(NSTableColumn *)tableColumn
	row:(int)row
{
	NSString *v = [voiceList objectAtIndex:row];
	NSDictionary *dict = [NSSpeechSynthesizer attributesForVoice:v];
	return [dict objectForKey:NSVoiceName];
}

- (void)tableViewSelectionDidChange:(NSNotification *)notification
{
	int row = (int)[tableView selectedRow];
	if (row == -1)
	{
		return;
	}
	
	NSString *selectedVoice = [voiceList objectAtIndex:row];
	[speechSynth setVoice:selectedVoice];
	NSLog(@"New voice = %@", selectedVoice);
}

@end
